package com.engine.budget.cmd;

import com.engine.budget.enums.Instruction;
import com.engine.budget.enums.VerifyMessage;
import com.engine.budget.manager.InstructionManager;
import com.engine.budget.util.VerifyUtil;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author DY
 * @date 2024/7/17 14:33
 * @description: 电商平台控制接口
 * @version 1.0
 */
public class EcomPlatCtrlCmd extends AbstractCommonCommand<Map<String,Object>> {

    private Map<String, Object> otherMap;

    private String logId;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {

        //返回数据
        Map<String, Object> result = new HashMap();
        RecordSetTrans rsTrans = new RecordSetTrans();
        try {
            this.logId = Util.null2String(otherMap.get("logId"));
            result.put("logId", logId);
            logger.info("外部系统调用电商平台控制接口cmd_start...LogID:"+logId);

            //业务参数
            JSONObject paramsObj = JSONObject.fromObject(params.get("params"));
            //docType	单据处理类型	instruction	指令	业务系统需要进行的操作类别代表
            String docType = paramsObj.getOrDefault("docType", "").toString();

            //转换后参数
            JSONArray paramsArr = VerifyUtil.ecomParamsChange(paramsObj);
            //返回数据数组
            JSONArray resArray = new JSONArray();
            //验证失败的表示
            boolean errFlag = false;

            RecordSet rs = new RecordSet();

            String sql = "select sfxrdb from uf_djkzclb where zhdjh = ?";

            for (int i = 0; i < paramsArr.size(); i++) {

                JSONObject data = paramsArr.getJSONObject(i);

                //执行单据号
                String exeDocNo = Util.null2String(data.getOrDefault("exeDocNo", ""));
                rs.executeQuery(sql, exeDocNo);
                if(rs.next()) {
                    otherMap.put("whiteZxdjh", "1");
                }else {
                    otherMap.put("whiteZxdjh", "0");
                }

                Map<String, Object> checkMap = VerifyUtil.verifyParams(data, otherMap, rs);
                otherMap.remove("whiteZxdjh");
                String status = Util.null2String(checkMap.getOrDefault("status", ""));
                if(!"1".equals(status) && !"-11".equals(status)) {
                    errFlag = true;
                }
                resArray.add(checkMap);
            }

            if (errFlag) {
                result.put("result", resArray);
                return result;
            }

            InstructionManager instructionManager = new InstructionManager();

            JSONArray newResArray = new JSONArray();
            for (int i = 0; i < paramsArr.size(); i++) {

                JSONObject data = paramsArr.getJSONObject(i);

                //执行单据号
                String exeDocNo = Util.null2String(data.getOrDefault("exeDocNo", ""));
                //是否写入数据
                String sfxrdb = "";
                rs.executeQuery(sql, exeDocNo);
                if(rs.next()) {
                    sfxrdb= Util.null2String(rs.getString("sfxrdb"));
                }


                JSONObject yzData = resArray.getJSONObject(i);

                String status = Util.null2String(yzData.getOrDefault("status", ""));
                if(!"-11".equals(status) && !"1".equals(sfxrdb)) {
                    Map<String, Object> resMap = instructionManager.execute(data, otherMap, rsTrans);
                    JSONObject resdata = yzData.getJSONObject("data");
                    resMap.put("data", resdata);
                    yzData = JSONObject.fromObject(resMap);
                }
                newResArray.add(yzData);

                InstructionManager.addInstructionLog(data, yzData, rs);

            }
            rsTrans.commit();

            JSONObject resObj = resChange(newResArray, paramsObj, docType);
            result.put("result", resObj);
            return result;
        }catch (Exception e) {
            rsTrans.rollback();
            Map<String, Object> errMap = VerifyMessage.XT_ERR.fromMap();
            errMap.put("status", -3);
            result.put("doc", "[]");
            result.putAll(errMap);
            logger.error("外部系统调用电商平台控制接口cmd——异常...err:"+e.getMessage(), e);
        }

        logger.info("外部系统调用电商平台控制接口cmd_end...LogID:"+logId);
        return result;
    }

    /**
     * @param: resArray
    paramsObj
    docType
     * @return: java.lang.String
     * @description: 返回参数转换
    */
    private JSONObject resChange(JSONArray resArray, JSONObject paramsObj, String docType) {

        int flag = 0;

        JSONArray docs = paramsObj.containsKey("doc") ? paramsObj.getJSONArray("doc") : new JSONArray();
        JSONArray newDocs = new JSONArray();
        int size = docs.size();
        for(Integer i = 0; i < size; i++) {
            JSONObject docObj = docs.getJSONObject(i);
            JSONArray rows = docObj.containsKey("rows") ? docObj.getJSONArray("rows") : new JSONArray();
            JSONArray newRows = new JSONArray();
            int size1 = rows.size();
            for(int j = 0; j < size1; j++) {
                JSONObject rowObj = rows.getJSONObject(j);

                JSONObject resObj = resArray.getJSONObject(flag);
                String status = resObj.getString("status");
                if("0".equals(status)) {
                    rowObj.put("success", "true");
                    rowObj.put("message", "执行成功");
                    if(Instruction.IA.getValue().equals(docType)) {
                        rowObj.put("budgetAmountAll", resObj.getOrDefault("budgetAmountAll", ""));
                        rowObj.put("budgetBalance", resObj.getOrDefault("budgetBalance", ""));
                        rowObj.put("percentage", resObj.getOrDefault("percentage", ""));
                    }
                }else {
                    rowObj.put("success", "false");
                    rowObj.put("message", resObj.getOrDefault("errorMessage", ""));
                }

                newRows.add(rowObj);
                flag++;
            }

            docObj.put("rows", newRows);
            newDocs.add(docObj);
        }

        paramsObj.put("doc", newDocs);


        return paramsObj;
    }


    public EcomPlatCtrlCmd(User user, Map<String, Object> params, Map<String, Object> otherMap) {
        this.user = user;
        this.params = params;
        this.otherMap = otherMap;
        this.otherMap.put("user",user);
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

}
